<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <coll-select v-model="query.collId" />
          </span>
          <span>
            <class-select v-model="query.orgId" @change="handleOrgChange" />
          </span>
          <span>
            <vxe-input v-model="query.keyword" clearable :placeholder="'搜索学生姓名'" size="medium"
              @keyup.enter.native="doSearch"></vxe-input>
          </span>
          <span>
            <el-select v-model="query.judgeState" placeholder="评分状态" size="small" clearable style="width: 100px;">
              <el-option label="未评分" :value="0"></el-option>
              <el-option label="已评分" :value="2"></el-option>
            </el-select>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="doSearch" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>

          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加成绩
            </el-button>
          </span>
        </div>
      </div>

      <!-- Section Table -->
      <vxe-table stripe auto-resize ref="table" :data="dataList" :loading="loading"
        :custom-config="tableCustomConfig" align="center">
        <vxe-table-column field="id" title="ID" width="160"></vxe-table-column>
        <vxe-table-column field="collTitle" title="活动" min-width="200"></vxe-table-column>
        <vxe-table-column field="schoolName" title="学校" min-width="200"></vxe-table-column>
        <vxe-table-column field="userName" title="学生姓名" width="120"></vxe-table-column>
        <vxe-table-column field="className" title="班级" width="120"></vxe-table-column>
        <vxe-table-column field="objectiveScore" title="客观题" width="80"></vxe-table-column>
        <vxe-table-column field="subjectiveScore" title="主观题" width="80"></vxe-table-column>
        <vxe-table-column field="totalScore" title="总分" width="80"></vxe-table-column>
        <vxe-table-column field="startAnswerAt" title="开始答题时间" width="160" :visible="false"></vxe-table-column>
        <vxe-table-column field="submitAt" title="提交时间" width="160"></vxe-table-column>
        <vxe-table-column field="judgeState" title="批改状态" width="100">
          <template v-slot="{ row }">
            <el-tag :type="row.judgeState === 2 ? 'success' : 'warning'">
              {{ row.judgeState === 2 ? '已评分' : '未评分' }}
            </el-tag>
          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="150" :visible="false"/>
        <vxe-table-column field="gmtModified" title="修改时间" width="150" :visible="false"/>

        <vxe-table-column title="操作" width="100" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        <el-button circle size="small" @click="handleTableCustom" icon="el-icon-menu"> </el-button>
      </div>

    </el-card>

    <EditDialog ref="editDialog" @success="handleSaveSuccess" />
  </div>
</template>

<script>
import api from '@/common/api';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import {DEFAULT_TABLE_CUSTOM_CONFIG} from "@/common/constants";
import EditDialog from './components/EditDialog.vue';
import CollSelect from "@/components/admin/ItechCollSelect.vue";
import ClassSelect from "@/components/admin/ClassSelect.vue";

export default {
  name: 'UserStatList',
  components: {
    CollSelect,
    SortOrderEditor,
    EditDialog,
    ClassSelect
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,

      // List data
      dataList: [],
      loading: false,
      total: 0,
      query: {
        orgId: [],
        keyword: '',
        currentPage: 1,
        limit: 10,
      }
    };
  },
  created() {
    this.getDataList();
  },
  methods: {

    // Get section list
    async getDataList() {
      try {
        this.loading = true;
        const params = Object.assign({}, this.query);
        delete params.orgId

        const {data} = await api.admin_getCollUserStatList(params);
        this.dataList = data.data.records;
        this.total = data.data.total;
      } finally {
        this.loading = false;
      }
    },

    // Filter operations
    doSearch() {
      this.query.currentPage = 1;
      this.getDataList();
    },

    // Handle pagination
    handleOrgChange(val) {
      const orgArr = val || []
      this.query.schoolId = orgArr[0]
      this.query.gradeId = orgArr[1]
      this.query.classId = orgArr[2]
      this.getDataList()
    },
    handleSizeChange(val) {
      this.query.limit = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getDataList();
    },
    handleTableCustom() {
      this.$refs.table?.openCustom()
    },

    // Handle CRUD operations
    handleAdd() {
      this.$refs.editDialog.open({});
    },
    handleEdit(row) {
      this.$refs.editDialog.open(row);
    },
    async handleDelete(row) {
      try {
        const confirmResult = await this.$confirm('确认删除该成绩?（将同时删除用户答案）', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });
        if (confirmResult !== 'confirm') {
          return;
        }
        await api.admin_deleteCollUserStat(row.id);
        this.$message.success('删除成功');
        this.getDataList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleStatusChange(row, enabled) {
      const data = { id: row.id, enabled };
      try {
        this.loading = true;
        await api.admin_saveCollUserStat(data);
        this.$message.success(`更新状态成功：已${enabled ? '启用' : '禁用'}`);
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    async handleSortUpdate(row, newValue) {
      const data = { id: row.id, sortOrder: newValue };
      try {
        this.loading = true;
        await api.admin_saveCollUserStat(data);
        this.$message.success('更新排序成功');
        this.getDataList();
      } finally {
        this.loading = false;
      }
    },
    handleSaveSuccess(data) {
      this.getDataList();
    },

    // Utils
    formatDate(date) {
      return date;
    },
  }
};
</script>

<style scoped>
.filter-row span {
  margin-right: 20px;
}

.filter-row span button {
  margin-top: 5px;
  margin-bottom: 5px;
}

.filter-row span div {
  margin-top: 8px;
}

.panel-options {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .filter-row span {
    margin-right: 5px;
  }

  .filter-row span div {
    width: 80%;
  }
}
</style>
